import { Component, OnInit, ViewChild } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { STColumn, STComponent, STData } from '@delon/abc/st';
import { SFComponent, SFDateWidgetSchema, SFSchema, SFUISchema, Widget } from '@delon/form';
import { ModalHelper, _HttpClient } from '@delon/theme';
import { NzModalService } from 'ng-zorro-antd/modal';
import { AccountManagemantService } from '../../services/account-managemant.service';

@Component({
  selector: 'app-partner-account-management-recorded-detail',
  styleUrls: ['./recorded-detail.component.less'],
  templateUrl: './recorded-detail.component.html'
})
export class PartnerAccountManagementRecordedDetailComponent implements OnInit {
  summaryObj: any = {
    waitRecordedAmount: 0,
    totalRebate: 0,
    taxPersonalSum: 0,
    recordedAmount: 0,
    ltdName: '',
    taxno: ''
  };
  @ViewChild('sfView', { static: false }) sfView!: SFComponent;
  schemaView!: SFSchema;
  uiView: SFUISchema = {};

  footerSummary = {
    total: 0,
    income: 0,
    spending: 0
  };

  detailRecord: any = {};
  changeRecord: any = {};
  changeRecordB: any = {};

  url = `/user`;
  schema: SFSchema = {};
  ui!: SFUISchema;
  @ViewChild('st') private readonly st!: STComponent;
  @ViewChild('stB') private readonly stB!: STComponent;
  @ViewChild('sf') private readonly sf!: SFComponent;

  columns: STColumn[] = [];
  billDetailColumns: STColumn[] = [];
  billDetailColumnsB: STColumn[] = [];
  showBillDetail = false;
  changeAccount = false;
  showBillDetailB = false;
  addd = false;
  billDetailList = [];
  billDetailListB = [];
  roleId = '';
  changeAmount: number = 0;
  constructor(public service: AccountManagemantService, public router: Router, public ar: ActivatedRoute, private nzModalService: NzModalService,) {
    this.roleId = this.ar.snapshot.params.id;
  }

  get reqParams() {
    return { ...this.sf?.value, partnerId: this.roleId };
  }

  get billDetailReqParams() {
    return {};
  }
  ngOnInit(): void {
    this.initSF();
    this.initST();
    this.getInvoiceSummary();
  }

  initSF() {
    this.schema = {
      properties: {
        ltdName: {
          type: 'string',
          title: '网络货运人',
          ui: {
            placeholder: '请输入',
            // allowClear: true,
            // asyncData: () => this.service.getNetworkFreightForwarder(),
            // visibleIf: {
            //   expand: (value: boolean) => value
            // }
          }
        }
      }
    };
    this.ui = { '*': { spanLabelFixed: 120, grid: { span: 8, gutter: 4 } } };
  }

  /**
   * 初始化数据列表
   */
  initST() {
    this.columns = [
      {
        title: '序号',
        className: 'text-center',
        width: '60px',
        format: (item: STData, col: STColumn, idx: number) => {
          return (this.st.pi * this.st.ps) - this.st.ps + idx + 1 + ''
        }
      },
      { title: '网络货运人', index: 'ltdName', className: 'text-center', width: 200 },
      { title: '银行类型', index: 'bankTypeName', className: 'text-center', width: 150 },
      { title: '虚拟账户', index: 'virtualAccount', className: 'text-center', width: 200 },
      { title: '返佣总额（元）', render: 'totalRebate', className: 'text-center', width: 180 },
      { title: '已入账金额（元）', render: 'recordedAmount', className: 'text-center', width: 180 },
      { title: '已代缴个税（元）', render: 'recordedTaxPersonal', className: 'text-center', width: 180 },
      { title: '入账中金额（元）', render: 'ongoingRecordedAmount', className: 'text-center', width: 180 },
      { title: '代缴中个税（元）', render: 'waitRecordedTaxPersonal', className: 'text-center', width: 180 },
      { title: '调整金额（元）', render: 'changeAmount', className: 'text-center', width: 180 },
      { title: '待入账金额（元）', render: 'waitRecordedAmount', className: 'text-right', width: 180 },
      {
        title: '操作',
        className: 'text-center',
        width: 150,
        fixed: 'right',
        buttons: [
          {
            text: '查看入账记录',
            acl: { ability: ['AN-RECORDED-DETAIL-viewRecord'] },
            click: _record => this.viewBookedRecord(_record)
          },
          {
            text: '查看账单明细',
            acl: { ability: ['AN-RECORDED-DETAIL-viewBill'] },
            click: _record => this.viewAccountDetail(_record)
          },
          {
            text: '调整待入账金额',
            acl: { ability: [''] },
            click: _record => this.changeStalyAccount(_record)
          }
        ]
      }
    ];
  }

  initBillDetailST() {
    this.billDetailColumns = [
      { title: '账单月份', render: 'month', className: 'text-center', width: '40%' },
      { title: '返佣金额（元）', render: 'profitAmountSum', className: 'text-center', width: '40%' },
      {
        title: '操作',
        className: 'text-center',
        width: '20%',
        buttons: [
          {
            text: '订单明细',
            click: _record => window.open(location.origin + `#/partner/rebate/record?ltdId=${_record?.ltdId}`)
          }
        ]
      }
    ];
  }
  initBillDetailSTB() {
    this.billDetailColumnsB = [
      { title: '调整金额（元）', render: 'changeAmount', className: 'text-center', width: '150px' },
      { title: '备注', index: 'remark', className: 'text-center', width: '200px' },
      { title: '操作时间', index: 'modifyTime', className: 'text-center', width: '200px' },
      { title: '操作人', index: 'createUserName', className: 'text-center', width: '150px' },
    ];
  }
  initSFNew() {
    this.schemaView = {
      properties: {
        smsVerifyCode: {
          title: '调整金额',
          type: 'string',
          description: '（“+”表示增加待入账金额，“-”表示减少待入账金额 ）',
          ui: {
            widget: 'custom',
            placeholder: '请输入金额',
            
            errors: {
            },
          },
        },
        remark: {
          title: '备注',
          type: 'string',
          maxLength: 50,
          ui: {
            placeholder: '请输入备注',
            widget: 'textarea',
            autosize: { minRows: 3, maxRows: 6 }
          }
        }
      },
      required: ['smsVerifyCode', 'remark'],
    };
    this.uiView = {
      '*': {
        spanLabelFixed: 100,
        grid: { span: 24 },
      },
    };
  }

  resetSF() {
    this.sf.reset();
    setTimeout(() => {
      this.st.reset();
    });
  }

  search() {
    this.st.load(1);
  }

  /**
   * 获取账单明细
   */
  getBillDetail(ltdId: string) {
    this.service.request(this.service.$api_get_bill_detail, { ltdId }).subscribe(res => {
      if (res) {
        this.billDetailList = res;
      }
    });
  }

  /**
   * 获取入账金额记录
   */
  getBillDetailB(ltdId: string) {
    let params = {
      ltdId: ltdId,
      partnerId: this.roleId ,
    }
    this.service.request(this.service.$api_get_getIncomeChangePage, params).subscribe(res => {
      if (res) {
        this.billDetailListB = res.records;
      }
    });
  }

  export() {}

  /**
   * 查看入账记录
   * @param record 当前行
   */
  viewBookedRecord(record: any) {
    window.open(location.origin + `#/partner/recorded/record?ltdId=${record?.ltdId}`);
  }

  /**
   * 查看账单明细
   * @param record 当前行
   */
  viewAccountDetail(record: any) {
    this.billDetailColumns = [];
    this.showBillDetail = true;
    this.initBillDetailST();
    this.detailRecord = record;
    this.getBillDetail(record?.ltdId);
  }
  /**
   * 查看调整金额
   * @param record 当前行
   */
   changeB(record: any) {
    // this.billDetailColumns = [];
    this.showBillDetailB = true;
    this.initBillDetailSTB();
    this.changeRecordB = record;
    this.getBillDetailB(record?.ltdId);
  }
  /**
   * 调整待入账金额
   * @param record 当前行
   */
   changeStalyAccount(record: any) {
   
    this.changeRecord = record;
    let params:any = {
      partnerId: this.roleId ,
      ltdId: record.ltdId,
      ltdName: record.ltdName,
    }
    this.service.request(this.service.$api_get_getPartnerLitAmountSummary, params).subscribe(res => {
      if (res) {
        this.changeAmount = Math.abs(res.waitRecordedAmount)
        if(res.waitRecordedAmount > 0) {
          this.addd = true;
        } else {
          this.addd = false;
        }
        this.changeAccount = true;
        this.initSFNew();
      }
    });
    // this.getBillDetail(record?.ltdId);
  }

  getInvoiceSummary() {
    this.service.request(this.service.$api_get_invoice_summary, { partnerId: this.roleId }).subscribe(res => {
      if (res) {
        this.summaryObj = res;
      }
    });
  }

  handleCancel() {
    this.showBillDetail = false;
    this.detailRecord = {};
  }
  handleCancelA() {
    this.changeAccount = false;
    this.changeRecord = {};
  }
  handleCancelB() {
    this.showBillDetailB = false;
    this.changeRecordB = {};
  }
  goBack() {
    window.history.go(-1);
  }
  deletes(value: number) {
    this.addd = false
  }
  add(value: number) {
    this.addd = true
  }
  handleOK() {
    console.log(this.sfView.value);

    if(!this.sfView.value?.remark || !this.changeAmount) {
      this.service.msgSrv.error('请填写必填项！')
      return
    }
    console.log(this.addd);
    
    let params:any = {
      remark: this.sfView.value?.remark,
      partnerId: this.roleId ,
      ltdId: this.changeRecord.ltdId
    }
    if(!this.addd) {
      params.changeAmount = -this.changeAmount
    } else {
      params.changeAmount = this.changeAmount
    }
    console.log(params);
    this.nzModalService.warning({
      nzTitle: `确定调整“${params.changeAmount > 0 ? '+' + params.changeAmount :  params.changeAmount}元”的待入账金额吗？`,
      nzOnOk: () => {
        this.service.request(this.service.$api_get_saveIncomeChange, params).subscribe((res) => {
          if(res) {
            console.log(res);
            this.service.msgSrv.success('修改成功！')
            this.changeAccount = false;
            this.st.load()
          }
        })
      }
    });
  
  }
}
